package com.ruoyi.qywx.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.callback.constants.ContactChangeType;
import com.ruoyi.qywx.callback.events.QywxEvent;
import com.ruoyi.qywx.callback.txl.PartyEncrypt;
import com.ruoyi.qywx.callback.txl.UserEncrypt;
import com.ruoyi.qywx.enums.QyExtEventEm;
import com.ruoyi.qywx.getway.api.SyncAppApi;
import com.ruoyi.qywx.getway.entity.QyContact;
import com.ruoyi.qywx.getway.entity.QyDept;
import com.ruoyi.qywx.service.inters.SyncQiyeService;
import com.ruoyi.qywx.service.inters.TxlCallbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author : hcl
 * @Date : 2023/8/4
 */
@Slf4j
@Service
public class TxlCallbackServiceImpl implements TxlCallbackService {
    @Autowired
    private SyncQiyeService syncQiyeService;

    /**
     * 部门变更与人员变更
     * 不处理标签变更事件
     */
    @Override
    public void contactChange(String xml, Meta meta) {
        JSONObject beanJson = xmlToJson(xml);
        String type = beanJson.getStr(ContactChangeType.TYPE_KEY);
        if (StrUtils.isEmpty(type)) return;
        switch (type) {
            case ContactChangeType.CREATE_PARTY:
                createParty(beanJson.toBean(PartyEncrypt.class), meta);
                break;
            case ContactChangeType.UPDATE_PARTY:
                updateParty(beanJson.toBean(PartyEncrypt.class), meta);
                break;
            case ContactChangeType.DELETE_PARTY:
                deleteParty(beanJson.toBean(PartyEncrypt.class), meta.getTeamId());
                break;
            case ContactChangeType.CREATE_USER:
                createUser(beanJson.toBean(UserEncrypt.class), meta);
                break;
            case ContactChangeType.UPDATE_USER:
                updateUser(beanJson.toBean(UserEncrypt.class), meta);
                break;
            case ContactChangeType.DELETE_USER:
                deleteUser(beanJson.toBean(UserEncrypt.class), meta);
                break;
        }
    }

    @Override
    @Async("qywxEventExecutor")
    public void externalEvent(String xml, Meta meta) {
        JSONObject beanJson = xmlToJson(xml);
        QywxEvent event = findExternalEvent(beanJson, meta);
        if (event != null) {
            event.eventExecute();
        }
    }

    private QywxEvent findExternalEvent(JSONObject beanJson, Meta meta) {
        String type = beanJson.getStr(ContactChangeType.TYPE_EVENT);
        if (StrUtils.isNotEmpty(type)) {
            return QyExtEventEm.valueOf(type.toUpperCase())
                    .exeternalEvent(syncQiyeService, beanJson, meta);
        }
        return null;
    }

    private void createUser(UserEncrypt user, Meta meta) {
        if (StrUtils.isNotBlank(user.getUserId())) {
            QyContact qyContact = SyncAppApi.userGet(meta, user.getUserId());
            if (qyContact != null) {
                syncQiyeService.createUser(qyContact, meta.getTeamId());
            }
        }
    }

    private void updateUser(UserEncrypt user, Meta meta) {
        if (StrUtils.isNotBlank(user.getUserId())) {
            QyContact qyContact = SyncAppApi.userGet(meta, user.getUserId());
            if (qyContact != null) {
                syncQiyeService.updateUser(qyContact, meta.getTeamId());
            }
        }
    }

    private void deleteUser(UserEncrypt user, Meta meta) {
        if (StrUtils.isNotBlank(user.getUserId())) {
            syncQiyeService.deleteUser(user.getUserId(), meta.getTeamId());
        }
    }

    public void deleteParty(PartyEncrypt party, Long teamId) {
        if (NumberUtils.isTrue(party.getId())) {
            syncQiyeService.deleteParty(party.getId(), teamId);
        }
    }

    private void updateParty(PartyEncrypt party, Meta meta) {
        if (NumberUtils.isTrue(party.getId())) {
            QyDept qyDept = SyncAppApi.departmentGet(meta, party.getId());
            if (qyDept != null) {
                PartyEncrypt encrypt = new PartyEncrypt();
                encrypt.setId(qyDept.getId());
                encrypt.setName(qyDept.getName());
                encrypt.setParentId(qyDept.getParentId());
                encrypt.setOrder(qyDept.getOrder());
                syncQiyeService.updateParty(encrypt, meta.getTeamId());
            }
        }
    }

    private void createParty(PartyEncrypt party, Meta meta) {
        if (NumberUtils.isTrue(party.getId())) {
            QyDept qyDept = SyncAppApi.departmentGet(meta, party.getId());
            if (qyDept != null) {
                PartyEncrypt encrypt = new PartyEncrypt();
                encrypt.setId(qyDept.getId());
                encrypt.setName(qyDept.getName());
                encrypt.setParentId(qyDept.getParentId());
                encrypt.setOrder(qyDept.getOrder());
                syncQiyeService.createParty(party, meta.getTeamId());
            }
        }
    }

    private JSONObject xmlToJson(String xml) {
        JSONObject json = XML.toJSONObject(xml);
        JSONObject contentJson = json.getJSONObject("xml");
        if (log.isDebugEnabled()) {
            log.debug("xml解析：{}", contentJson);
        }
        return contentJson;
    }
}
